package io.properties;

import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

/**
 * @author Cheng Jun
 * Description: Properties 属性类，底层是Hashtable
 * @version 1.0
 * @date 2022/8/14 22:30
 * @see Properties
 */
public class PropertiesExample {

    public static void main(String[] args) throws IOException {
        // 读取 properties 文件中的属性名和值
        // readProperties();
        storeProperties();
    }


    private static void readProperties() throws IOException {
        Properties properties = new Properties();
        String fileName = PropertiesExample.class.getResource("").getPath() + "mysql.properties";
        System.out.println(fileName);
        properties.load(new FileReader(fileName));
        // 相对路径这样写不行，有空再找找有没有其它的办法使用相对路径创建流
        // properties.load(new FileReader("./mysql.properties"));
        // 在控制台输出 mysql.properties 中的内容，注释不会输出
        properties.list(System.out);
        Enumeration<?> propertyNames = properties.propertyNames();
        while (propertyNames.hasMoreElements()) {
            String propertyValue = properties.getProperty((String) propertyNames.nextElement());
            System.out.println(propertyValue);
        }
    }

    private static void storeProperties() throws IOException {
        Properties properties = new Properties();
        properties.setProperty("charset", "utf-8");
        // \u6210\u541B 文件中出现utf的编码是正常的
        // 重新设置就是修改属性，Properties继承了Hashtable
        properties.setProperty("author", "cauchy6317成君");
        properties.setProperty("email", "152***@163.com");
        String fileName = "src/io/properties/mysql2.properties";
        System.out.println(fileName);
        FileOutputStream fileWriter = new FileOutputStream(fileName);
        properties.store(fileWriter, "我是注释");
        fileWriter.close();
    }
}
